package eoeProject.edenOfEast.core;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.request.Request;

import eoeProject.edenOfEast.bean.EOEUserBean;
import eoeProject.edenOfEast.dataBase.DB_EOE_USER;

public final class EOEAuthenticatedWebSession extends AuthenticatedWebSession {

	private static final long serialVersionUID = 1L;

	private static EOEUserBean userBean = new EOEUserBean();

	// private Roles role;

	public EOEAuthenticatedWebSession(Request request) {
		super(request);
	}

	@Override
	public boolean authenticate(final String userName, final String password) {
		try {
			String pass = PassDigest.getInstance().getPassDigest(password,
					userName);
			SQLMaker sql = new SQLMaker(DB_EOE_USER.TABLE_NAME,
					SQLMaker.SQL_TYPE_SELECT);
			sql.addExpEquals(DB_EOE_USER.USER_NAME, userName);
			sql.addExpEquals(DB_EOE_USER.PASSWORD, pass);
			ResultSet rs = DBConnector.getInstance().get(sql.getSQL());
			if (rs.next()) {

				setUserId(rs.getInt(DB_EOE_USER.USER_ID));
				setUserName(rs.getString(DB_EOE_USER.USER_NAME));
				// if(rs.getInt(DB_EOE_USER.ROLE) == 0){
				// role = new Roles(Roles.ADMIN);
				// }
				// else{
				// role = new Roles(Roles.USER);
				// }
				this.signIn(true);
				rs.close();
				return true;

			}
			rs.close();
			return false;
		} catch (SQLException e) {
			System.out.println("EOEAuthenticatedWebSession Exception: "
					+ e.getMessage());
			return false;
		}
	}

	@Override
	public Roles getRoles() {
		if (isSignedIn()) {
			// if (ADMIN.equals(userBean.getUserName())) {
			// return new Roles(Roles.ADMIN);
			// }

			return new Roles(Roles.USER);
		}

		return null;
	}

	public static Integer getUserId() {
		return userBean.getUserId();
	}

	public static void setUserId(Integer user_id) {
		userBean.setUserId(user_id);
	}

	public static String getUserName() {
		return userBean.getUserName();
	}

	public static void setUserName(String user_name) {
		userBean.setUserName(user_name);
	}

	public EOEUserBean getUserBean() {
		return userBean;
	}

}